<template>
    <div v-show="initShow && isUseDraw" class="layout">
        <div v-if="authInfo?.is_set_official != 2 && showTitle" class="title-warn">
            <span class="title-warn-icon">
                <el-icon color="#FAAD14"><WarningFilled /></el-icon>
                <span>群裂变活动需要配置公众号，请先在列表左上角完成配置</span>
            </span>
            <span class="title-warn-icon" @click="closeTitle">
                <el-icon><Close /></el-icon>
            </span>
        </div>
        <div class="container">
            <ZWGroup
                ref="GroupingRef"
                :type="30"
                :group-id="group_id"
                :get-group-fun="handleGetGroupList"
                @submit="handleGroupSubmit" />
            <div class="container-right">
                <div class="container-form">
                    <ZwSearchForm
                        row-num="3"
                        :default-expand="false"
                        :option="searchOption"
                        @search="search"
                        @expand="onExpand"
                        @reset="reset" />
                </div>
                <div class="container-table">
                    <div class="container-table-account">
                        <ShareAccountConfiguration
                            :is-show-mini-app="false"
                            :type="10"
                            :no-need-loading="true"
                            @auth="fissionAuth" />
                        <el-button type="primary" @click="openNew">新建活动</el-button>
                    </div>
                    <ZwTable
                        ref="tableRef"
                        class="table-box"
                        tab-h="initial"
                        :fetch-api="fetchApi()"
                        :row-key="getRowKey"
                        :close-loading="true"
                        :option="tableOption"
                        :fetch-params="state.searchParams"
                        @dataChange="dataChange">
                    </ZwTable>
                </div>
            </div>
        </div>
    </div>
    <!-- 无数据页面 -->
    <NoData v-show="initShow && !isUseDraw" @submit="goUse"></NoData>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
    <!-- 推广弹框 -->
    <ShareConfiguration
        v-if="isShowConfiguration"
        ref="shareConfigurationRef"
        v-model:show="isShowConfiguration"
        :activity_id="content_id"
        :account-type="accountType"
        :type="10" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SMART_MARKETING_DRAINAGE_GROUP_FISSION' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import ShareAccountConfiguration from '@/components/common/ShareAccountConfiguration.vue';
import ShareConfiguration from './components/ShareConfiguration.vue';
import NoData from './components/NotData.vue';
import { ElMessage, ElButton } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
import { groupInfo } from '@/api/smartMarketing/drainage/channelCode/index';
import { groupFissionList, groupFissionEnd, groupFissionDel } from '@/api/smartMarketing/drainage/groupFission';
import { getCreateList } from '@/api/common';
import { ref, reactive, computed, onActivated, onMounted, nextTick } from 'vue';
import { reSize } from '@/utils/utils';
import { useStore } from '@/store';
import { endLoading, startLoading } from '@/utils/request';
import { isCachePage } from '@/utils/utils';

import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
const DeletdialogRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const GroupingRef: any = ref(null);
const store = useStore();
const delId = ref('');
const requestFlag = ref<boolean>(false);
const checkNum = ref<number>(0);
const currentParams = ref<any>(null);
const group_id = ref<string>('all'); //分组id
const shareConfigurationRef = ref<HTMLElement>();
const isShowConfiguration = ref<boolean>(false); // 推广弹窗
const content_id = ref<number>(0);
const accountType = ref<number>(1);
const isType = ref<string>('');
const authInfo = ref<any>(null); //判断公众号是否显示
const initShow = ref<boolean>(false);
const showTitle = ref<boolean>(true);
const isUseDraw = ref(false); // 是否是当前企业
const defaultParams = {
    group_id: 'all', //分组ID
    activity_name: '', //群裂变名称
    create_uid: [], //创建人
    activity_time: [], //活动有效期
    activity_status: 0 //活动状态
};

// 二次包装处理分组接口方法，拿取总数判断头部是否显示
const handleGetGroupList = async (data: any) => {
    const res = await groupInfo(data);
    return res;
};

const handleGroupSubmit = (v: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupFission',
        query: { group_id: v.id }
    });
    group_id.value = v.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value.clearSelection();
};

const tableRef: any = ref<HTMLElement | null>(null);

const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '活动名称',
            name: 'activity_name',
            value: '',
            type: 'input',
            placeholder: '请输入活动名称'
        },

        {
            label: '活动状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择活动状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: 0 },
                        { name: '未开始', id: 1 },
                        { name: '进行中', id: 2 },
                        { name: '已结束', id: 3 },
                        { name: '提前结束', id: 4 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建人',
            name: 'create_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '活动有效期',
            name: 'activity_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD',
            defaultTime: [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)],
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    tableRef.value.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), ...v, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v: any) => {
    tableRef.value.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
// 状态颜色
const StatusColorOption = {
    未开始: '#EAEAEA',
    进行中: '#2FB6E4',
    已结束: '#F14144',
    提前结束: '#ff0004'
};
// 表格
const tableOption = [
    {
        prop: 'activity_name',
        label: '活动名称',
        minWidth: 300
    },
    {
        prop: 'status_name',
        label: '活动状态',
        width: 150,
        render({ row }) {
            return (
                <div
                    class="status-point"
                    style={{
                        '--status-bgcolor': StatusColorOption[row.status_name] ?? '#D8D8D8'
                    }}>
                    {row.status_name}
                </div>
            );
        }
    },
    {
        prop: 'reward_step',
        label: '奖品层级',
        minWidth: 100
    },

    {
        prop: 'activity_time',
        label: '活动有效期',
        width: 350,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <span>{row.begin_date}</span>
                            <span> - </span>
                            <span>{row.end_date}</span>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'join_num',
        label: (
            <div class="box-item-div">
                <span>参与人数</span>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="生成过该活动助力海报的用户数量，不管是否有被助力过"
                    placement="top">
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </div>
        ),
        width: 150
    },
    {
        prop: 'finish_num',
        label: (
            <div class="box-item-div">
                <span>完成人数</span>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="参与该活动且完成任务的人数（完成一级任务计入，</br>若助力回退后不满足一级任务条件人数会扣减）"
                    raw-content
                    placement="top">
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </div>
        ),
        width: 150
    },
    {
        prop: 'fission_num',
        label: (
            <div class="box-item-div">
                <span>裂变人数</span>
                <el-tooltip class="box-item" effect="dark" content="助力人数+失效人数" placement="top">
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </div>
        ),
        width: 150
    },
    {
        prop: 'retain_num',
        label: (
            <div class="box-item-div">
                <span>群净留存人数</span>
                <el-tooltip class="box-item" effect="dark" content="进群人数-退群人数" placement="top">
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </div>
        ),
        width: 150
    },
    {
        prop: 'add_friend_num',
        label: (
            <div class="box-item-div">
                <span>净增好友数</span>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="通过该活动添加了引流成员的用户数量（不包含被删除好友）"
                    placement="top">
                    <el-icon class="box-icon">
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </div>
        ),
        width: 150
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 100
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        width: 210,
        fixed: 'right',
        isOperate: true,
        //1:未开始 2:进行中 3:已结束 4:提前结束
        option: [
            {
                name: '编辑',
                authCode: 'EDIT',
                isRender: ({ row }: any) => row.activity_status !== 3 && row.activity_status !== 4,
                click: (row: any) => openEdit(row)
            },
            {
                name: '删除',
                authCode: 'DEL',
                isRender: ({ row }: any) => row.activity_status !== 2,
                click: (row: any) => toDelete(row)
            },
            {
                name: '复制',
                authCode: 'COPY',
                click: (row: any) => openCopy(row)
            },
            {
                name: '推广',
                authCode: 'PLUG',
                click: (row: any) => toPopularize(row)
            },
            {
                name: '提前结束',
                authCode: 'END',
                isRender: ({ row }: any) =>
                    row.activity_status !== 1 && row.activity_status !== 3 && row.activity_status !== 4,
                click: (row: any) => toForward(row)
            },
            {
                name: '数据',
                authCode: 'STATISTICS',

                isRender: ({ row }: any) => row.activity_status !== 1,
                click: (row: any) => openRecord(row)
            }
        ]
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const dataChange = (res: any) => {
    if (res.data) initShow.value = true;
    if (checkNum.value === 0) {
        const currentCorp = store.getters['user/getCurrentCorp'];
        const isUser = JSON.parse(localStorage.getItem('zw-isDraw-fission'));
        if (res.data.length == 0) {
            if (isUser && isUser == currentCorp) {
                isUseDraw.value = true;
            } else {
                isUseDraw.value = false;
            }
        } else {
            isUseDraw.value = true;
        }
    }
    checkNum.value++;
};

const fetchApi = () => {
    getTableH();
    return groupFissionList;
};

// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 关闭顶部未配置公众号
const closeTitle = () => {
    showTitle.value = false;
};
// 判断是否是当前企业
const isCurrentFirm = () => {
    groupFissionList({ page: 1, page_size: 15, ...defaultParams, group_id: 'all' }).then((res: any) => {
        const currentCorp = store.getters['user/getCurrentCorp'];
        const isUser = JSON.parse(localStorage.getItem('zw-isDraw-fission'));
        if (res.data.length == 0) {
            if (isUser && isUser == currentCorp) {
                isUseDraw.value = true;
            } else {
                isUseDraw.value = false;
            }
        } else {
            isUseDraw.value = true;
        }
    });
};
// 获取配置权限
const fissionAuth = (val: any) => {
    !!val && (authInfo.value = val);
};
// 去跳转列表页
const goUse = (data: number | string) => {
    localStorage.setItem('zw-isDraw-fission', JSON.stringify(data));
    isCurrentFirm();
};

// 新增 需要传公众号id
const openNew = (row: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupFission/detail',
        query: { type: 'new', group_id: group_id.value, official_account_id: authInfo.value?.official_account_id }
    });
};
// 编辑 需要传公众号id
const openEdit = (row: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupFission/detail',
        query: { type: 'edit', id: row.id, group_id: group_id.value }
    });
};
// 复制
const openCopy = (row: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupFission/detail',
        query: { type: 'copy', id: row.id, group_id: group_id.value }
    });
};
// 跳转数据
const openRecord = (row: any) => {
    const { activity_status, real_end_date, end_date: finish_date } = row;
    const end_date = activity_status === 4 ? real_end_date : finish_date;
    router.push({
        path: '/smartMarketing/drainage/groupFission/statistics',
        query: { activity_status: row.activity_status, id: row.id, end_date }
    });
};
// 删除活动
const toDelete = (row: any) => {
    delId.value = row.id;
    isType.value = 'del';
    DeletdialogRef.value.appDialog.visible = true;
    DeletdialogRef.value.appDialog.title = '删除';
    DeletdialogRef.value.content = '确定要删除该活动吗？';
};
// 提前结束活动
const toForward = (row: any) => {
    delId.value = row.id;
    isType.value = 'forward';
    DeletdialogRef.value.appDialog.visible = true;
    DeletdialogRef.value.appDialog.title = '提前结束';
    DeletdialogRef.value.content = '确认要提前结束该活动吗';
};
// 推广
const toPopularize = (row: any) => {
    accountType.value = 1;
    content_id.value = row.id;
    // content_id.value = 2714;
    isShowConfiguration.value = true;
};
// 删除&&提前结束确定
const onSubmit = async () => {
    startLoading();
    try {
        switch (isType.value) {
            case 'del':
                await groupFissionDel({ id: delId.value });
                reloadTable();
                ElMessage.success('删除成功');
                break;
            case 'forward':
                await groupFissionEnd({ id: delId.value });
                reloadTable();
                ElMessage.success('提前结束成功');
                break;
        }
    } catch (error) {
        endLoading();
    }
};
// 表格的自适应高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const onExpand = () => {
    getTableH();
};
onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await GroupingRef.value.getGroup(30);
        }
        tableRef.value.clearSelection();
        await GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
onMounted(() => {
    reSize(getTableH);
    // isCurrentFirm();
});
</script>

<style lang="scss" scoped>
.layout {
    height: calc(100vh - 142px);
    display: flex;
    flex-direction: column;

    .title-warn {
        background: #fffbe6;
        border-radius: 2px;
        border: 1px solid #ffe58f;
        padding: 9px 17px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title-warn-icon {
            display: flex;
            cursor: pointer;
        }

        span {
            font-size: 14px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: rgb(0 0 0 / 65%);
            margin-left: 8px;
            cursor: pointer;
        }
    }

    .container {
        flex: 1;
        display: flex;
        overflow: hidden;

        .container-right {
            flex: 1;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            overflow: hidden;

            .container-form {
                border: 1px solid #eaeaea;
            }

            .container-table {
                flex: 1;
                display: flex;
                flex-direction: column;
                overflow: hidden;
                box-sizing: border-box;
                border: 1px solid #eaeaea;
                background-color: #fff;
                padding: 16px;
                margin-top: 16px;

                .zw-table {
                    display: flex;
                    flex-direction: column;
                    flex: 1;
                    overflow: hidden;

                    :deep(.el-table) {
                        flex: 1;

                        .el-table__empty-block {
                            position: absolute;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                        }
                    }
                }

                .container-table-account {
                    display: flex;
                    justify-content: space-between;
                }
            }
        }

        :deep(.box-item-div) {
            display: flex;
            line-height: 1;
        }

        :deep(.box-icon) {
            margin-left: 4px;
            color: #969696;
            background: #fff;
            border-radius: 50%;
        }

        :deep(.status-point) {
            --status-bgcolor: #ffd500;

            &::before {
                content: '';
                display: inline-block;
                width: 8px;
                height: 8px;
                margin-right: 8px;
                background-color: var(--status-bgcolor);
                border-radius: 4px;
            }
        }
    }
}
</style>
